package com.example.zwgt.yrfk.ui.access.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.IDCardParams;
import com.baidu.ocr.sdk.model.IDCardResult;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.example.zwgt.yrfk.R;
import com.example.zwgt.utils.FileUtil;
import com.example.zwgt.yrfk.base.mvpbase.BasePresenter;
import com.example.zwgt.yrfk.base.mvpbase.baseImpl.BaseActivity;
import com.example.zwgt.yrfk.view.PhotoPopupWindow;


import java.io.File;


import butterknife.BindView;
import butterknife.OnClick;

public class AddUserActivity extends BaseActivity {


    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.rl_top)
    RelativeLayout rlTop;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_sex)
    EditText etSex;
    @BindView(R.id.et_sfz)
    EditText etSfz;
    @BindView(R.id.et_address)
    EditText etAddress;
    @BindView(R.id.ocr)
    TextView ocr;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_marriage)
    EditText etMarriage;
    @BindView(R.id.et_zin)
    EditText etZin;
    @BindView(R.id.et_home)
    EditText etHome;
    @BindView(R.id.et_nsr)
    EditText etNsr;
    @BindView(R.id.et_xl)
    EditText etXl;
    @BindView(R.id.et_gzdw)
    EditText etGzdw;
    @BindView(R.id.et_gsxz)
    EditText etGsxz;
    @BindView(R.id.et_dwdh)
    EditText etDwdh;
    @BindView(R.id.et_dwdz)
    EditText etDwdz;
    @BindView(R.id.et_dwfwnx)
    EditText etDwfwnx;
    @BindView(R.id.et_yxq)
    EditText etYxq;
    @BindView(R.id.et_birthday)
    EditText etBirthday;
    @BindView(R.id.et_ethnic)
    EditText etEthnic;
    @BindView(R.id.et_qfjg)
    EditText etQfjg;
    private PhotoPopupWindow mPhotoPopupWindow;
    private boolean hasGotToken = false;
    private static final int REQUEST_CODE_CAMERA = 102;
    private static final int REQUEST_CODE_PICK_IMAGE_FRONT = 201;
    private static final int REQUEST_CODE_PICK_IMAGE_BACK = 202;



    @Override
    public int getLayoutId() {
        return R.layout.act_adduser;
    }

    /**
     * 入口
     *
     * @param context
     */
    public static void startAction(Context context) {
        Intent intent = new Intent(context, AddUserActivity.class);
        context.startActivity(intent);
    }


    @Override
    protected void initViews() {
        initAccessToken();
        mPhotoPopupWindow=new PhotoPopupWindow(this);
    }


    @OnClick({R.id.iv_back, R.id.ocr, R.id.add_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ocr:
                ocrPupwindow();
                break;
            case R.id.add_next:
                NextAddUserActivity.startAction(this);
                break;
        }
    }

    /**
     * 创建popUpwindow  选择身份证正反面
     */
    private void ocrPupwindow() {
        View rootView = LayoutInflater.from(AddUserActivity.this)
                .inflate(R.layout.activity_main, null);
        mPhotoPopupWindow.showAtLocation(rootView,
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        mPhotoPopupWindow.setSelectOnItemOnclick(new PhotoPopupWindow.SelectOnItemOnclick() {
            @Override
            public void selectType(int position) {
                if(position==1){
                    showFront();
                    mPhotoPopupWindow.dismiss();
                }else {
                    showBack();
                    mPhotoPopupWindow.dismiss();
                }
            }
        });
    }

    //身份证反面(国徽)
    private void showFront() {
        Intent intent = new Intent(AddUserActivity.this, CameraActivity.class);
        intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                FileUtil.getSaveFile(getApplication()).getAbsolutePath());
        intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_BACK);
        startActivityForResult(intent, REQUEST_CODE_CAMERA);
    }

    //身份证正面(名字)
    private void showBack() {
        if (!checkTokenStatus()) {
            return;
        }
        Intent intent = new Intent(AddUserActivity.this, CameraActivity.class);
        intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                FileUtil.getSaveFile(getApplication()).getAbsolutePath());
        intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
        startActivityForResult(intent, REQUEST_CODE_CAMERA);
    }

    private boolean checkTokenStatus() {
        if (!hasGotToken) {
            Toast.makeText(getApplicationContext(), "token还未成功获取", Toast.LENGTH_LONG).show();
        }
        return hasGotToken;
    }

    /**
     * 权限检查
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            initAccessToken();
        } else {
            Toast.makeText(getApplicationContext(), "需要android.permission.READ_PHONE_STATE", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 回调结果
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PICK_IMAGE_FRONT && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            String filePath = getRealPathFromURI(uri);
            recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, filePath);
        }

        if (requestCode == REQUEST_CODE_PICK_IMAGE_BACK && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            String filePath = getRealPathFromURI(uri);
            recIDCard(IDCardParams.ID_CARD_SIDE_BACK, filePath);
        }
        if (requestCode == REQUEST_CODE_CAMERA && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                String contentType = data.getStringExtra(CameraActivity.KEY_CONTENT_TYPE);
                String filePath = FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath();
                if (!TextUtils.isEmpty(contentType)) {
                    if (CameraActivity.CONTENT_TYPE_ID_CARD_FRONT.equals(contentType)) {
                        recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, filePath);
                    } else if (CameraActivity.CONTENT_TYPE_ID_CARD_BACK.equals(contentType)) {
                        recIDCard(IDCardParams.ID_CARD_SIDE_BACK, filePath);
                    }
                }
            }
        }
    }

    private void recIDCard(String idCardSide, String filePath) {
        IDCardParams param = new IDCardParams();
        param.setImageFile(new File(filePath));
        // 设置身份证正反面
        param.setIdCardSide(idCardSide);
        // 设置方向检测
        param.setDetectDirection(true);
        // 设置图像参数压缩质量0-100, 越大图像质量越好但是请求时间越长。 不设置则默认值为20
        param.setImageQuality(20);
        if (idCardSide.equals("front")) {
            OCR.getInstance(this).recognizeIDCard(param, new OnResultListener<IDCardResult>() {
                @Override
                public void onResult(IDCardResult result) {
                    if (result != null) {
                        //正面数据
                        etName.setText(result.getName().toString());
                        etSex.setText(result.getGender().toString());
                        etSfz.setText(result.getIdNumber().toString());
                        etAddress.setText(result.getAddress().toString());
                        etBirthday.setText(result.getBirthday().toString());
                        etEthnic.setText(result.getEthnic().toString());
                    }
                }

                @Override
                public void onError(OCRError error) {
                    alertText("", error.getMessage());
                }
            });
        } else {
            OCR.getInstance(this).recognizeIDCard(param, new OnResultListener<IDCardResult>() {
                @Override
                public void onResult(IDCardResult result) {
                    if (result != null) {
                        //反面数据(身份证有效期)
                        etYxq.setText(result.getSignDate().toString() + "-" + result.getExpiryDate().toString());
                        etQfjg.setText(result.getIssueAuthority().toString());
                    }
                }

                @Override
                public void onError(OCRError error) {
                    alertText("", error.getMessage());
                }
            });
        }


    }

    private String getRealPathFromURI(Uri contentURI) {
        String result;
        Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) { // Source is Dropbox or other similar local file path
            result = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }


    private void alertText(final String title, final String message) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(AddUserActivity.this);
                alertDialog.setTitle(title)
                        .setMessage(message)
                        .setPositiveButton("确定", null)
                        .show();
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放内存资源
        OCR.getInstance(this).release();
    }

    @Override
    public BasePresenter initPresenter() {
        return null;
    }


    /**
     * 以license文件方式初始化 ,ocr文件必须的方法
     */
    private void initAccessToken() {
        OCR.getInstance(this).initAccessToken(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken accessToken) {
                String token = accessToken.getAccessToken();
                hasGotToken = true;
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                alertText("licence方式获取token失败", error.getMessage());
            }
        }, getApplicationContext());
    }

}
